package triDataStruct;

import triFileSystem.*;
import triStorage.*;
import transaction.*;

//From String -> Int
public class InsertableMap extends BufferObject {

	private int inodePageId;
	
	private PageDir inode;
	
	private IWriter writer;
	
	//private Object lock = new Object();
	//private RWLock lock = new RWLock();
	
	public InsertableMap() {
		super();
	}

	public void reset(int inodePageId, PageDir inode, IWriter writer) {
		if (this.writer != null)
			this.writer.dispose();

		this.inodePageId = inodePageId;
		this.inode = inode;
		this.writer = writer;
	}
	
	@Override
	public int getKey() {
		return inodePageId;
	}
	
	public PageDir getInodeSnapshot(Transaction tx) {
		return inode.copy(tx);
	}
	
	public long getFilePos(Transaction tx) {
		lock.lockRead(tx);
		try {
			return writer.getWritePos();
		}
		finally {
			lock.unlockRead(tx);
		}
	}
	
	public void insert(String key, int value, Transaction tx) {
		lock.lockWrite(tx);
		try {
			writer.appendInt(1, tx);
			writer.appendString(key, tx);
			writer.appendInt(value, tx);
		}
		finally {
			lock.unlockWrite(tx);
		}
	}
	
	public void dispose() {
		writer.dispose();
	}
}
